// 导入 Vue 3 Composition API 的核心函数
import { computed, defineComponent, ref, onMounted } from "vue";
// 导入 Element Plus 组件
import { ElButton, ElCol, ElDialog, ElMessage, ElRow } from "element-plus";
// 导入 Formily 相关组件和函数
import { DatePicker } from "@formily/element-plus";
import { createForm } from "@formily/core";
// 导入自定义组件和 hooks
import SchemaForm from "@/components/SchemaForm";
import usePageTable, { useTableSelect } from "@/hooks/usePageTable";
// 导入 API 函数
import {
  addAwardRecord,
  deleteAwardRecord,
  editAwardRecord,
  getAwardList,
  getAwardRecordList,
} from "@/api/scholarship";
import { listUser, getUser } from "@/api/system/user";
import { getStudent } from "@/api/student";
// 导入类型定义
import type { Award, AwardRecord } from "@/types/scholarship";
import type { User } from "@/types/user";

// 使用 defineComponent 来定义 Vue 组件，这有助于 TypeScript 类型推断
export default defineComponent({
  // setup 函数是 Vue 3 Composition API 的入口点
  setup() {
    // 创建一个 Formily 表单实例
    const form = createForm<AwardRecord>({});
    // 使用 ref 创建响应式变量
    const title = ref("");
    const open = ref(false);
    const tableData = ref<AwardRecord[]>([]);

    // 添加奖学金颁奖的处理函数
    const handleAdd = () => {
      open.value = true;
      title.value = "添加奖学金颁奖";
    };

    // 查看/修改奖学金颁奖记录的处理函数
    const handleView = async (row: AwardRecord) => {
      form.setValues({ ...row }, "overwrite");
      open.value = true;
      title.value = "修改奖学金颁奖";
    };

    // 使用自定义 hook 创建奖学金表格选择器
    const { TableSelect: AwardTableSelect, data: awardTableData } =
      useTableSelect<Award, number>(
        { getList: getAwardList },
        [
          { key: "title", title: "奖学金类型" },
          {
            key: "range",
            title: "申请时间范围",
            render: (row: Award) => {
              return `${row.startTime.replaceAll(
                "-",
                "."
              )}-${row.endTime.replaceAll("-", ".")}`;
            },
          },
        ],
        "single",
        (row: Award) => row.applicationAwardTypeId
      );

    // 根据 ID 获取奖学金类型的辅助函数
    const getAwardType = (applicationAwardTypeId: number) =>
      awardTableData.value.find(
        (item) => item.applicationAwardTypeId === applicationAwardTypeId
      )?.applicationAwardType;

    // 使用 computed 创建计算属性，生成奖学金类型的选项列表
    const AwardTypeEnums = computed(() =>
      awardTableData.value.map((item) => ({
        label: item.applicationAwardType,
        value: item.applicationAwardTypeId,
      }))
    );

    // 使用自定义 hook 创建表格、搜索和查询表单
    const { Table, handleSearch, QueryForm } = usePageTable<AwardRecord>(
      {
        fields: [
          { key: "studentName", title: "学生姓名", type: "Input" },
          {
            key: "applicationAwardTypeId",
            title: "奖学金类型",
            type: "Select",
            enums: AwardTypeEnums,
          },
        ],
        getList: async (...args) => {
          const result = await getAwardRecordList(...args);
          tableData.value = result.rows;
          return result;
        },
      },
      [
        { key: "applicationAwardType", title: "奖学金类型" },
        { key: "awardLevel", title: "奖学金级别" },
        { key: "studentName", title: "学生姓名" },
        { key: "awardAmount", title: "奖学金金额" },
        { key: "awardDate", title: "颁奖日期" },
        { key: "studentCode", title: "学号" },
        { key: "studentGrade", title: "年级" },
        { key: "studentClass", title: "班级" },
        { key: "studentCollege", title: "学院" },
        {
          key: "operate",
          title: "操作",
          // 使用 JSX 渲染操作按钮
          render: (row: AwardRecord) => (
            <>
              <ElButton
                link
                type="primary"
                icon="Edit"
                onClick={() => handleView(row)}
              >
                修改
              </ElButton>
              <ElButton
                link
                type="danger"
                icon="Delete"
                onClick={() => handleDelete(row)}
              >
                删除
              </ElButton>
            </>
          ),
        },
      ]
    );

    // 获取并记录用户数据的异步函数
    const fetchAndLogUserData = async () => {
      await Promise.all(
        tableData.value.map(async (record) => {
          try {
            const userData = await getUser(record.studentId);
            if (userData && userData.data && userData.data.userName) {
              const userName = userData.data.userName;
              try {
                const studentData = await getStudent(userName);
                if (studentData && studentData.data) {
                  record.studentCode = studentData.data.studentCode;
                  record.studentGrade = studentData.data.studentGrade;
                  record.studentClass = studentData.data.studentClass;
                  record.studentCollege = studentData.data.studentCollege;
                  console.log(`学号: ${studentData.data.studentCode}`);
                  console.log(`年级: ${studentData.data.studentGrade}`);
                  console.log(`班级: ${studentData.data.studentClass}`);
                  console.log(`学院: ${studentData.data.studentCollege}`);
                } else {
                  console.log(
                    "studentData not found or structure is different than expected"
                  );
                }
              } catch (studentError) {
                console.error(
                  `Error fetching student data for userName: ${userName}`,
                  studentError
                );
              }
            } else {
              console.log(
                "userName not found or userData structure is different than expected"
              );
            }
          } catch (error) {
            console.error(
              `Error fetching user data for studentId: ${record.studentId}`,
              error
            );
          }
        })
      );
    };

    // 使用 onMounted 生命周期钩子在组件挂载后执行初始化操作
    onMounted(async () => {
      await handleSearch();
      await fetchAndLogUserData();
    });

    // 表单提交处理函数
    const submit = () => {
      form.submit(async (values) => {
        if (values.awardId) {
          await editAwardRecord(values);
        } else {
          await addAwardRecord(values);
        }
        open.value = false;
        ElMessage.success("操作成功");
        await handleSearch();
        await fetchAndLogUserData();
      });
    };

    // 删除奖学金记录的处理函数
    const handleDelete = async (row: AwardRecord) => {
      await deleteAwardRecord(row.awardId);
      ElMessage.success("操作成功");
      await handleSearch();
      await fetchAndLogUserData();
    };

    // 使用自定义 hook 创建学生表格选择器
    const { TableSelect: StudentTableSelect, data: studentTableData } =
      useTableSelect<User, number>(
        {
          getList: listUser,
          fields: [
            { title: "身份证号", key: "userName", type: "Input" },
            { title: "姓名", key: "nickName", type: "Input" },
          ],
          initValues: { pageSize: 10, pageNum: 1 },
        },
        [
          { key: "userName", title: "身份证号" },
          { key: "nickName", title: "姓名" },
          { key: "phonenumber", title: "手机号码" },
        ],
        "single",
        (row: User) => row.userId
      );

    // 根据学生 ID 获取学生姓名的辅助函数
    const getStudentName = (studentId: number) =>
      studentTableData.value.find((item) => studentId === item.userId)
        ?.nickName;

    // 定义表单模式（schema）
    const schema = {
      type: "object",
      properties: {
        layout: {
          type: "void",
          "x-component": "FormLayout",
          "x-component-props": { labelWidth: 100 },
          properties: {
            studentId: {
              type: "string",
              title: "颁奖学生",
              "x-component": StudentTableSelect,
              "x-decorator": "FormItem",
              required: true,
            },
            studentName: {
              type: "string",
              "x-reactions": {
                dependencies: [".studentId"],
                fulfill: { state: { value: "{{getStudentName($deps[0])}}" } },
              },
            },
            applicationAwardTypeId: {
              type: "string",
              "x-component": AwardTableSelect,
              "x-decorator": "FormItem",
              title: "奖学金类型",
              required: true,
            },
            applicationAwardType: {
              type: "string",
              "x-reactions": {
                dependencies: [".applicationAwardTypeId"],
                fulfill: { state: { value: "{{getAwardType($deps[0])}}" } },
              },
            },
            awardAmount: {
              type: "string",
              title: "奖学金金额",
              "x-component": "Input",
              "x-decorator": "FormItem",
              "x-validator": "number",
              required: true,
            },
            awardLevel: {
              type: "string",
              title: "奖学金级别",
              "x-component": "Select",
              enum: [
                { label: "一等奖", value: "一等奖" },
                { label: "二等奖", value: "二等奖" },
                { label: "三等奖", value: "三等奖" },
              ],
              "x-decorator": "FormItem",
              required: true,
            },
            awardDate: {
              type: "string",
              title: "颁奖时间",
              "x-component": "DatePicker",
              "x-decorator": "FormItem",
              required: true,
            },
          },
        },
      },
    };

    // 返回渲染函数，使用 JSX 语法
    return () => (
      <div class="p-2 md:p-4 h-full">
        <QueryForm />
        <ElRow gutter={10} class="mb-4">
          <ElCol span={1.5}>
            <ElButton type="primary" plain icon="Plus" onClick={handleAdd}>
              新增
            </ElButton>
          </ElCol>
        </ElRow>
        <Table />

        <ElDialog
          v-model={open.value}
          title={title.value}
          width="850px"
          append-to-body
        >
          {{
            default: () => (
              <SchemaForm
                form={form}
                schema={schema}
                components={{ DatePicker }}
                scope={{ getStudentName, getAwardType }}
              />
            ),
            footer: () => (
              <>
                <ElButton type="primary" onClick={submit}>
                  确 定
                </ElButton>
                <ElButton onClick={() => (open.value = false)}>取 消</ElButton>
              </>
            ),
          }}
        </ElDialog>
      </div>
    );
  },
});
